import 'package:flutter/material.dart';
import 'package:flutter_study/sqflite/db_util/dbmanager.dart';
import 'package:flutter_study/sqflite/db_util/user_vo.dart';
import 'package:flutter_study/utils/toast.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:math';
import 'dart:ui';

class SqflitePage extends StatefulWidget {
  final String title;

  SqflitePage({Key key, this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return SqfliteState();
  }
}

class SqfliteState extends State<SqflitePage> {
  var items = 0;
  List<User> itemsList = List();
  var nameController = TextEditingController();
  var psdController = TextEditingController();
  var nickNameController = TextEditingController();
  var currentItem = -1;

  // 光标跳转的输入框对象
  FocusNode firstTextFieldNode = FocusNode();
  FocusNode secondTextFieldNode = FocusNode();
  FocusNode thirdTextFieldNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    var appbar = AppBar(
      title: Text(this.widget.title),
    );

    var toolbar = Container(
      margin: EdgeInsets.only(left: 4, right: 4),
      child: Row(
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              _creatTb();
            },
            child: Text('创建表'),
          ),
          RaisedButton(
            onPressed: () {
              _insertData(context);
            },
            child: Text('插入数据'),
          ),
          RaisedButton(
            onPressed: () {
              _findAll();
            },
            child: Text('查询数据'),
          ),
          RaisedButton(
            onPressed: () {
              _del(currentItem);
            },
            child: Text('删除'),
          ),
        ],
      ),
      height: 45,
    );

    var textEditOutlineInputBorder = OutlineInputBorder(
      borderRadius: BorderRadius.circular(5),
      borderSide: BorderSide(color: Theme.of(context).primaryColor),
    );

    return Scaffold(
        appBar: appbar,
        body: Container(
          child: Column(
            children: <Widget>[
              Container(
                padding: const EdgeInsets.all(0),
                margin: const EdgeInsets.all(8),
                child: TextField(
                  controller: nameController,
                  // 键盘格式
                  keyboardType: TextInputType.number,
                  // 光标颜色
                  cursorColor: Colors.black,
                  // 键盘动作按钮，如“下一步”
                  textInputAction: TextInputAction.next,
                  // 键盘动作按钮点击之后执行的代码：
                  //光标切换到指定的输入框
                  onEditingComplete: () =>
                      FocusScope.of(context).requestFocus(secondTextFieldNode),
                  // 文本样式
                  style: new TextStyle(color: Colors.black),
                  // 是否自动获取焦点
                  autofocus: false,
                  focusNode: firstTextFieldNode,
                  decoration: InputDecoration(
                    labelText: ('用户名'),
                    //// 输入框文本周边的距离
                    contentPadding: const EdgeInsets.all(12),
                    hintText: '请输入用户名',
                    border: textEditOutlineInputBorder,
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.all(0),
                margin: const EdgeInsets.all(8),
                child: TextField(
                  controller: psdController,
                  focusNode: secondTextFieldNode,
                  decoration: InputDecoration(
                    labelText: '密码',
                    contentPadding: const EdgeInsets.all(12),
                    hintText: '请输入密码',
                    border: textEditOutlineInputBorder,
                  ),
                  style: new TextStyle(color: Colors.black),
                  // 是否自动获取焦点
                  autofocus: false,
                ),
              ),
              Container(
                padding: const EdgeInsets.all(0),
                margin: EdgeInsets.all(8),
                child: TextField(
                  style: TextStyle(color: Colors.black),
                  focusNode: thirdTextFieldNode,
                  controller: nickNameController,
                  decoration: InputDecoration(
                    labelText: '昵称',
                    contentPadding: EdgeInsets.all(12),
                    hintText: '请输入昵称',
                    border: textEditOutlineInputBorder,
                  ),
                  // 是否自动获取焦点
                  autofocus: false,
                ),
              ),
              toolbar,
              Expanded(
                child: ListView.builder(
                  padding: new EdgeInsets.all(5.0),
                  itemBuilder: (BuildContext context, index) {
                    return GestureDetector(
                        onTap: () {
                          setState(() {
                            currentItem = index;
                          });
                        },
                        child: Container(
                          color:
                              currentItem == index ? Colors.grey : Colors.white,
                          child: Column(
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  Expanded(
                                    flex: 1,
                                    child: Text(
                                        '${itemsList[index].autoId}'.trim()),
                                  ),
                                  Expanded(
                                    flex: 2,
                                    child: Text(
                                      itemsList[index].name.trim(),
                                    ),
                                  ),
                                  Expanded(
                                    flex: 2,
                                    child: Text(itemsList[index].psd.trim()),
                                  ),
                                  Expanded(
                                    flex: 3,
                                    child: Text(
                                        '${itemsList[index].nickName.trim()}+测试过啥合法很舒服的卡卡发货'),
                                  ),
                                ],
                              ),
                              Divider(
                                height: 0.5,
                                color: Colors.black,
                              )
                            ],
                          ),
                        ));
                  },
                  itemCount: itemsList.length,
                ),
              )
            ],
          ),
        ));
  }

  @override
  void initState() {
    super.initState();
    //1、初始化数据库
    DBManager.init();
  }

  void _creatTb() async {
    UserProvider().createTable();
//    await DBManager.createTable('Test2',
//        'CREATE TABLE Test2 (id INTEGER PRIMARY KEY AUTOINCREMENT , name TEXT, value INTEGER, num REAL)');
  }

  _insertData(
    BuildContext context,
  ) async {
    var u = User();
    if (nameController == null || nameController.text.length <= 0) {
      print('用户名不能为空');
      showMsg(context, '用户名不能为空');
      return;
    }
    if (psdController.text.length <= 0) {
      showMsg(context, '密码不能为空');
      return;
    }
    if (nickNameController.text.length <= 0) {
      showMsg(context, '昵称不能为空');
      return;
    }
    u.name = nameController.text;
    u.psd = psdController.text;
    u.nickName = nickNameController.text;
    User res = await UserProvider().insert(u);
    nameController.text = "";
    psdController.text = "";
    nickNameController.text = "";
    FocusScope.of(context).requestFocus(firstTextFieldNode); //设置焦点
    print('插入数据的id：${res.autoId}');
    _findAll();
  }

//    Database db = DBManager.getDb();
//    String sql = 'INSERT INTO Test2 (name, value, num) VALUES("测试数据2", ${Random().nextInt(1000)},${Random().nextInt(1000)})';
//    int res = await db.rawInsert(
//        sql);
//    print('===>执行语句:${sql}');
//    print('插入ID:${res}');
//    return res;

  _findAll() async {
    List<User> listUser = await UserProvider().findAll();
    for (int i = 0; i < listUser.length; i++) {
      print(listUser[i].toString());
    }
    setState(() {
      itemsList.clear();
      itemsList.addAll(listUser);
      currentItem = -1;
    });
//    Database db = DBManager.getDb();
//    List<Map> res = await db.rawQuery('select * from Test2');
//    for (int i = 0; i < res.length; i++) {
//      print("${res[i]['name']} ===== ${res[i]['value']}");
//    }
  }

  showMsg(BuildContext context, String msg) {
    //Scaffold.of(context).showSnackBar(new SnackBar(content: Text(msg)));
    Toast.toast(context, msg);
  }

  void _del(int currentItem) {
    print('删除：${currentItem}');
    if ((currentItem) == -1) {
      Toast.toast(context, "请选择一个");
      return;
    }

    UserProvider().delete(itemsList[currentItem].autoId);
    setState(() {
      itemsList.removeAt(currentItem);
      this.currentItem = -1;
    });
  }
}
